
const Token = require('./token')
const {aesDecrypt} = require('./crypto')
async function auth(req,res,next){
    let authTxt = ''
    if(req.headers.authtxt){
        authTxt = aesDecrypt(req.headers.authtxt)
    }
   const token = new Token(req.headers.authorization)
   const from = req.headers.from || ''  // 系统标志，即来自哪个系统:主要用来区别公众号，不同的系统使用不同的公众号
   const tokenData = await token.verifyToken()
   if(tokenData){  // 有效token
        // 根据token获取用户id和用户类型（token："5e8c1c87c2a20b38d871cec2###-1",'###'前面是用户id，后面是用户类型）
       // console.log("!!!!!",tokenData)
        const tokenId = tokenData.id
        const [userId,userType,tax] = tokenId.split("###")
        // 把userId，userType传给下一个处理函数
        req.userId = userId
        req.userType = userType
        req.tax = tax // 税务机关用户
        req.from = from
        if(authTxt){
            req.corpid = authTxt.split("##")[0]
            req.agentId = authTxt.split("##")[1]
        }
        
        next()
   }else{
       res.json({
           code:5004,//5001:非法的token; 5002:其他客户端登录了; 5004:Token 过期了;
           data:'',
           message:'token过期或者无效'
       })
   }   
}
async function isLogin(req,res,next){
    let authTxt = ''
    if(req.headers.authtxt){
        authTxt = aesDecrypt(req.headers.authtxt)
    }
    const token = new Token(req.headers.authorization)
    const from = req.headers.from || ''
    const tokenData = await token.verifyToken()
    if(tokenData){  // 有效token
         const tokenId = tokenData.id
         const [userId,userType,tax] = tokenId.split("###")
         // 把userId，userType传给下一个处理函数
         req.userId = userId
         req.userType = userType
         req.tax = tax  // 税务机关用户
         req.from = from
         if(authTxt){
            req.corpid = authTxt.split("##")[0]
            req.agentId = authTxt.split("##")[1]
         }
         
         next()
    }else{
        req.from = from
        if(authTxt){
            req.corpid = authTxt.split("##")[0]
            req.agentId = authTxt.split("##")[1]
        }
        next()
    }   
 }
module.exports = {
    auth,
    isLogin
}